import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { NativeService } from '../native.service'
import { AppAvailability } from '@ionic-native/app-availability/ngx';
import { GaoDeLocation } from '@ionic-native/gao-de-location/ngx';

declare var BMap, BMAP_ANCHOR_BOTTOM_LEFT, BMAP_MAPTYPE_CONTROL_MAP, BMAP_SATELLITE_MAP, BMAP_STATUS_SUCCESS;

@Component({
  selector: 'app-baidumap',
  templateUrl: './baidumap.page.html',
  styleUrls: ['./baidumap.page.scss'],
})
export class BaidumapPage implements OnInit {
  map: any;
  drive;
  dlsgs = [];
  markers = []
  geoc = new BMap.Geocoder();

  constructor(
    private el: ElementRef,
    private gaoDeLocation: GaoDeLocation,

    private appAvailability: AppAvailability, private nativeService: NativeService,) { }

  ngOnInit() {
    this.map = new BMap.Map("map_container");
    this.map.centerAndZoom('济南', 12);
    this.map.addEventListener("moveend", (e) => {
      //事件
      let center = this.map.getCenter();
      console.log(center);
    });
    // 添加控件
    var Scaleopts = { // 配置
      anchor: BMAP_ANCHOR_BOTTOM_LEFT, //控件的停靠位置
      //BMAP_ANCHOR_TOP_LEFT     控件将定位到地图的左上角
      //BMAP_ANCHOR_TOP_RIGHT    控件将定位到地图的右上角
      //BMAP_ANCHOR_BOTTOM_LEFT  控件将定位到地图的左下角
      //BMAP_ANCHOR_BOTTOM_RIGHT 控件将定位到地图的右下角
      offset: new BMap.Size(10, 10), //控件的水平偏移值
    }
    var Navopts = {
      anchor: '',
      offset: new BMap.Size(10, 80), //控件的水平偏移值
      type: '', //平移缩放控件的类型
      //BMAP_NAVIGATION_CONTROL_LARGE  标准的平移缩放控件（包括平移、缩放按钮和滑块）
      //BMAP_NAVIGATION_CONTROL_SMALL  仅包含平移和缩放按钮
      //BMAP_NAVIGATION_CONTROL_PAN    仅包含平移按钮
      //BMAP_NAVIGATION_CONTROL_ZOOM   仅包含缩放按钮
      showZoomInfo: '', //是否显示级别提示信息
      enableGeolocation: '' //控件是否集成定位功能，默认为false
    }
    var mapcopi = {
      type: BMAP_MAPTYPE_CONTROL_MAP,
      offset: new BMap.Size(10, 80), //控件的水平偏移值
    }
    this.map.addControl(new BMap.NavigationControl(Navopts));// 平移缩放控件
    this.map.addControl(new BMap.ScaleControl(Scaleopts));// 比例尺
    this.map.addControl(new BMap.MapTypeControl(mapcopi));// 地图类型

    this.drive = new BMap.DrivingRoute(this.map, {
      renderOptions: {
        map: this.map,
        panel: 'r-result',
        autoViewport: true
      }, onMarkersSet: function (routes) {
        // that.seticon(routes);
      }
    });
  }
  addmark() {
    this.dlsgs = [{ LNG: 117.037251, LAT: 36.681097, NAME: '名砸', MAINPEOPLE: '百年', SIZE: 'SIZE', PLACE: 'PLACE' },
    { LNG: 117.017991, LAT: 36.667666, NAME: '名砸1', MAINPEOPLE: '百年', SIZE: 'SIZE', PLACE: 'PLACE' },
    { LNG: 117.038544, LAT: 36.646589, NAME: '名砸2', MAINPEOPLE: '百年', SIZE: 'SIZE', PLACE: 'PLACE' },
    { LNG: 117.047743, LAT: 36.67635, NAME: '名砸3', MAINPEOPLE: '百年', SIZE: 'SIZE', PLACE: 'PLACE' },
    ];
    this.adddlsgToMap();
  }
  search() {
    // 百度地图API功能
    // var map = new BMap.Map("l-map");            // 创建Map实例
    // map.centerAndZoom(new BMap.Point(116.404, 39.915), 11);
    var that = this;
    var local = new BMap.LocalSearch(this.map, {
      renderOptions: { map: this.map, },
      // onMarkersSet: function (pois) {
      //   that.map.clearOverlays();
      //   for (let i = 0; i < pois.length; i++) {
      // var sgIcon = new BMap.Icon(require("../../assets/img/markicon.png"), new BMap.Size(20, 20));
      // mark.setIcon(sgIcon);
      // that.map.addOverlay(mark);
      // var mark = pois[i].marker;
      // (function (j) {
      //   setTimeout(function () {
      //     var mark = pois[i].marker;
      //     var sgIcon = new BMap.Icon(require("../../assets/img/markicon.png"), new BMap.Size(20, 20));
      //     mark.setIcon(sgIcon);
      //     that.map.addOverlay(mark);
      //   }, 1000);
      // })(i);
      //   }
      // }
    });
    local.search("文物");
  }
  searchnearby() {
    var that = this;
    var local = new BMap.LocalSearch(this.map, {
      renderOptions: { map: this.map, panel: "r-result", selectFirstResult: false },
      onMarkersSet: function (pois) {

        console.log("---------onMarkersSet---------");
        // that.map.clearOverlays();
        for (let i = 0; i < pois.length; i++) {
          var sgIcon = new BMap.Icon(require("../../assets/img/markicon.png"), new BMap.Size(20, 20));
          var mark = pois[i].marker;
          mark.setIcon(sgIcon);
          that.map.removeOverlay(mark);
        }
      },
      onInfoHtmlSet(poi) {
        console.log("---------onInfoHtmlSet---------");
        // // debugger
        // var sgIcon = new BMap.Icon(require("../../assets/img/markicon.png"), new BMap.Size(30, 30));
        // var mark = poi.marker;
        // mark.setIcon(sgIcon);
      }
      ,
      onResultsHtmlSet(container) {
        console.log("---------onResultsHtmlSet---------");
      }
      ,
      onSearchComplete: function (results) {
        console.log("---------onSearchComplete---------");
        var myicon = new BMap.Icon(require("../../assets/img/markicon.png"), new BMap.Size(20, 20));

        // debugger
        if (local.getStatus() == BMAP_STATUS_SUCCESS) {
          // 判断状态是否正确
          // for (var j = 0; j < results.length; j++) {
          //   var keys = results[j];
          //   console.log(keys.keyword);
          //   {
          //     for (var i = 0; i < keys.getCurrentNumPois(); i++) {
          //       var point = new BMap.Point(keys.getPoi(i).point.lng, keys.getPoi(i).point.lat);
          //       var marker = new BMap.Marker(point, { icon: myicon });
          //       this.map.addOverlay(marker);
          //     }
          //   }
          // }
          that.dlsgs = [];
          for (var i = 0; i < results.getCurrentNumPois(); i++) {
            var poi = results.getPoi(i);
            var point = poi.point;
            // s.push(poi.title + ", " + poi.address);
            var dlsg = { LNG: point.lng, LAT: point.lat, NAME: poi.title, MAINPEOPLE: '年', SIZE: '', PLACE: poi.address };
            that.dlsgs.push(dlsg);
            var marker = new BMap.Marker(point, { icon: myicon });
            that.map.addOverlay(marker);
          }
          that.adddlsgToMap();
          // document.getElementById("log").innerHTML = s.join("<br>");
        }
      }
    });
    local.searchNearby("厕所", new BMap.Point(117.037251, 36.681097), 300);
  }
  openmapapp() {
    if (this.nativeService.isAndroid()) {
      // console.log("--------------------------------------openmap");
      this.appAvailability.check("com.baidu.BaiduMap").then(
        (yes: boolean) => {
          var uri = "bdapp://map/show?center=36.66975,117.129525&zoom=7&traffic=on&bounds=36.578454,116.885761,36.738267,117.180692&src=andr.baidu.openAPIdemo";
          var inApp = window.open(uri, '_blank', 'location=yes');
        },
        (no: boolean) => {
          alert("您尚未安装百度地图app");

        }
      );   //IOS
    } else if (this.nativeService.isIOS()) {
      // console.log("--------------------------------------openmap");
      this.appAvailability.check("com.baidu.BaiduMap").then(
        (yes: boolean) => {
          var uri = "baidumap://map/show?center=36.66975,117.129525&zoom=7&traffic=on&bounds=36.578454,116.885761,36.738267,117.180692&src=ios.baidu.openAPIdemo";
          var inApp = window.open(uri, '_blank', 'location=yes');
        },
        (no: boolean) => {
          alert("您尚未安装百度地图app");

        }
      );   //IOS
    }
  }


  adddlsgToMap() {
    this.map.clearOverlays();
    this.markers = [];
    var str = "<div style='background: rgb(255, 255, 255);'> " +
      "<ol style='list-style: none; padding: 0px; margin: 0px;'>";

    for (var i = 0; i < this.dlsgs.length; i++) {
      // debugger
      var data = this.dlsgs[i];
      var ggPoint = new BMap.Point(data.LNG, data.LAT);
      // var sgIcon = new BMap.Icon("http://api.map.baidu.com/images/markers.png", new BMap.Size(20, 20), {
      //   imageOffset: new BMap.Size(-23, -25 * i)
      // });

      let marker = new BMap.Marker(ggPoint);
      // this.map.panTo(data.points[0]);
      marker.setPosition(ggPoint);
      this.map.addOverlay(marker);
      this.markers.push(marker);
      var opts = {
        width: 0,     // 信息窗口宽度
        height: 0,     // 信息窗口高度
        title: data.NAME, // 信息窗口标题
        // enableMessage: true//设置允许信息窗发送短息
      };
      this.addClickHandler(this.map, opts, "</br>年限：" + data.MAINPEOPLE + "</br>规模：" + data.SIZE + "</br>地理位置：" + data.PLACE, marker);

      //                    console.log(JSON.stringify(poi));

    }



  }
  listclick(str) {
    var marker = this.markers[str];
    var point = marker.point;

    this.map.panTo(point);

  }
  addClickHandler(map, opts, content, marker) {
    var con = this;
    marker.addEventListener("click", function (e) {
      con.openInfo(map, opts, content, e)
    }
    );
  }
  openInfo(map, opts, content, e) {
    var p = e.target;
    var point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);
    var infoWindow = new BMap.InfoWindow(content, opts);  // 创建信息窗口对象 
    map.openInfoWindow(infoWindow, point); //开启信息窗口
  }
  changemaptype() {
    this.drive.search('齐鲁软件学院', "英雄山");
  }
  showresult = false;
  opendiv() {
    this.showresult = true;
  }

  close() {
    this.showresult = false;
  }
  nearbysearch(e, ty) {
    this.showresult = false;
  }
  dingwei() {

    this.gaoDeLocation.getCurrentPosition({
      androidOption: {  /**
        * location mode
        */
        locationMode: 1,
        /**
         * gps first
         */
        gpsFirst: true,
        /**
         * Http timeOut
         */
        HttpTimeOut: 1000,
        /**
         * Location interval
         */
        interval: 1,
        /**
         * Open reverse address
         */
        needAddress: true,
        /**
         * once location
         */
        onceLocation: true,
        /**
         * once location latest
         */
        onceLocationLatest: true,
        /**
         * location protocol
         */
        locationProtocol: 1,
        /**
         * sensor enable
         */
        sensorEnable: true,
        /**
         * wifi scan
         */
        wifiScan: true,
        /**
         * location cache enable
         */
        locationCacheEnable: true,
      }, iosOption: {

        /**
         * pauses location updates automatically
         */
        pausesLocationUpdatesAutomatically: 'YES',
        /**
         * allows background location updates
         */
        allowsBackgroundLocationUpdates: 'YES',
        /**
         * location timeout
         */
        locationTimeout: 1000,

      }
    })
      .then((res) => {
        if (res.longitude != undefined) {
          alert('定位成功' + res);
          //116.38924235026042---35.175052897135416--
          console.log('getCurrentPositi--------' + res.longitude + '---' + res.latitude + "--" + res.city + '--' + res.country + "" + res.formattedAddress);
          var point = new BMap.Point(res.longitude, res.latitude);

          var sgIcon = new BMap.Icon(require("../../assets/img/mark.png"), new BMap.Size(20, 20));
          var marker = new BMap.Marker(point, { icon: sgIcon });
          this.map.addOverlay(marker);

          this.showInfo(point);
          console.log(res);
        }
      })
      .catch((error) => {
        alert('定位失败');
        console.log('Error getting location' + error);
      });

  }
  showInfo(ggPoint) {
    var temp = this;
    var convertor = new BMap.Convertor();
    var pointArr = [];
    pointArr.push(ggPoint);
    convertor.translate(pointArr, 3, 5, function (data) {//坐标转换 高德地图定位坐标转百度
      console.log('showInfo 1' + '坐标转换中.................');
      if (data.status === 0) {
        console.log('showInfo' + '坐标转换成功.................' + data.points[0].lat + "-=-=---" + data.points[0].lng);
        var sgIcon = new BMap.Icon(require("../../assets/img/markicon.png"), new BMap.Size(20, 20));
        var marker = new BMap.Marker(data.points[0], { icon: sgIcon });
        temp.map.addOverlay(marker);



        temp.geoc.getLocation(data.points[0], function (rs) {//百度逆地理编码
          var addComp = rs.addressComponents;
          console.log('showInfo nibilibianma .' + addComp);
          var info = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
          alert(info);
        });
      } else {
        console.log('Error getting location' + '坐标转换失败.................');
      }
    })
  }
}
